package com.example.gw_back_end.interceptors;

import com.example.gw_back_end.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class ClientTypeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String clientType = request.getHeader("X-Client-Type");
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (isValidAccountType(clientType, claims)) {
            System.out.println("访问端：" + clientType);
        } else {
            System.out.println("访问端未知，拒绝访问");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false; // 拦截请求
        }

        return true;
    }

    // 账户类型判断
    private boolean isValidAccountType(String clientType,Map<String, Object> claims) {
        Integer accountType = (Integer) claims.get("accountType");
        if (clientType.equals("Admin") && accountType.equals(3)) {
            return true;
        } else if (clientType.equals("Vendor") && ( accountType.equals(3) || accountType.equals(2) || accountType.equals(1))) {
            return true;
        } else return clientType.equals("Client") && (accountType.equals(3) || accountType.equals(2) || accountType.equals(1) || accountType.equals(0));
    }
}
